using UnityEngine;

namespace VoxelEngine
{
	public class ChunkObject : MonoBehaviour
	{
		[SerializeField]
		private MeshFilter _chunkMesh;

		[SerializeField]
		private MeshCollider _chunkCollider;

		[SerializeField]
		private MeshRenderer _chunkRenderer;

		private Chunk _chunk;

		private bool _dirty;

		private static Material[] _materials;

		private bool _shouldRefreshChunk;

		public MeshFilter ChunkMesh
		{
			get
			{
				return _chunkMesh;
			}
			set
			{
				_chunkMesh = value;
			}
		}

		public MeshCollider ChunkCollider
		{
			get
			{
				return _chunkCollider;
			}
			set
			{
				_chunkCollider = value;
			}
		}

		private void Awake()
		{
			if (_materials == null)
			{
				_materials = new Material[3]
				{
					BaseWorldController.VoxelPlayerData.VoxelWorldData.OpaqueMaterial,
					BaseWorldController.VoxelPlayerData.VoxelWorldData.TransparentMaterial,
					BaseWorldController.VoxelPlayerData.VoxelWorldData.CutoutMaterial
				};
			}
			_chunkRenderer.materials = _materials;
		}

		public static void Clear()
		{
			_materials = null;
		}

		public void SetChunk(Chunk chunk)
		{
			_chunk = chunk;
		}

		public void SetDirty()
		{
			_dirty = true;
		}

		public void LateUpdate()
		{
			if (_shouldRefreshChunk)
			{
				_shouldRefreshChunk = false;
				_chunk.RefreshChunkMesh();
			}
			if (_dirty)
			{
				_shouldRefreshChunk = true;
				_dirty = false;
			}
		}
	}
}
